<?php 

class ModelStockMoneyOut extends Model {
	public function getstatus(){
		$sql = "select * from money_out_status";
		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getrefertype(){
		$sql = "select * from refer_type";
		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function addout($data,$user_id,$username){
		$data['operator_id']=$user_id;
		$data['operator']=$username;
		$data['date_added'] = date('Y-m-d H:i:s');
		$id = M("money_out")->data($data)->add();
		if ($data['refer_type_id']==2) {
			M("money_out")->data(array('trader_type'=>1))->where(array('money_out_id'=>$id))->save();
		}

		if ($data['refer_type_id']==3||$data['refer_type_id']==7) {
			M("money_out")->data(array('trader_type'=>2))->where(array('money_out_id'=>$id))->save();
		}
	}

	public function getList($page, $filter){
    	$list = M('money_out')
		->join('left join  `money_type` r on r.money_type_id=money_out.refer_type_id')
		->join('left join  `money_out_status` s on s.money_out_status_id=money_out.status')
		->field('money_out.*,r.type_name as name,s.name as status_name')
		->order('money_out.date_added DESC')
		->where($filter)
		->page($page)->limit($this->config->get('config_limit_admin'))->select();
		 // echo M('money_out')->getlastsql();
		return $list; 
    }

    public function getListCount($filter){
    	$total = M('money_out')
		->where($filter)
		->count();
		return $total; 
    }

    public function cancel($money_out_id){
		return M('money_out')->where(array('money_out_id'=>$money_out_id))->data(array('status'=>3,'date_modified'=>date('Y-m-d H:i:s')))->save();
	}
	public function recover($money_out_id){
		return M('money_out')->where(array('money_out_id'=>$money_out_id))->data(array('status'=>1,'date_modified'=>date('Y-m-d H:i:s')))->save();
	}
	public function pay($money_out_id){
		return M('money_out')->where(array('money_out_id'=>$money_out_id))->data(array('status'=>2,'date_modified'=>date('Y-m-d H:i:s'),'pay_time'=>date('Y-m-d H:i:s')))->save();
	}
	public function addMoHistory($money_out_id, $user_id,$comments){
		$username = M('user')->where(array('user_id'=>$user_id))->getField('username');
		$data = array(
					'money_out_id'=>$money_out_id, 
		  			'user_id'=>$user_id,
		  			'operator_name'=>$username,
		  		 	'comment'=>$comments, 
					'date_added'=>date('Y-m-d H:i:s'));
		M('money_out_history')->data($data)->add();
	}

	public function getMoById($money_out_id){
		return M('money_out')->join('left join  `refer_type` r on r.refer_type_id=money_out.refer_type_id')
		->join('left join  `money_out_status` s on s.money_out_status_id=money_out.status')
		->field('money_out.*,r.name,s.name as status_name')->
		where(array('money_out_id'=>$money_out_id))->find();
	}
	
	public function getOutById($data){
		return M('stock_in')
		->field('refer_id,buy_money,in_date')->
		where(array('refer_type_id'=>$data['refer_type_id'],'refer_id'=>$data['refer_id'],'status'=>2))->select();
	}
	public function editout($res,$money_out_id){
		$pa = M("money_out")->where(array('money_out_id'=>$money_out_id))->getField('paid');
		$data['paid'] = (float)$pa + $res['paidadd'];
		$data['date_modified'] = date('Y-m-d H:i:s');
		$data['pay_time'] = date('Y-m-d H:i:s');
		$data['status'] = 2;
		M("money_out")->where(array('money_out_id'=>$money_out_id))->data($data)->save();
		M("money_out")->getlastsql();
	}

	public function getProduct($in_id,$refer_type_id,$refer_id){
		$polist =M('stock_in')
		->where(array('stock_in.in_id' => $in_id, 'stock_in.refer_type_id' => $refer_type_id, 'stock_in.refer_id' => $refer_id))
		->field('stock_in.*')
		->find();
		if (!empty($polist)) {
			$where =' in_id='.$polist['in_id'].' and op.option_value_id=pov.option_value_id' ;
			$polist['product']=M('stock_in_detail')
			->join('left join product_option_value pov on pov.product_code=stock_in_detail.product_code')
			->join('left join product pro on pro.product_id=pov.product_id')
			->join('left join product_description pd on pd.product_id=pov.product_id')
			->join('left join  inventory i on pov.product_code=i.product_code')
			->join('left join  option_value_description op on op.option_id=pov.option_id')
			->distinct('pov.product_code')
			->field('stock_in_detail.*,pd.name,pd.product_id,pov.product_code,op.name as oname,pro.sku,i.position1,i.position2')
			 ->where($where)
			// ->group('pov.product_code')
			->select();
		}
		
		// echo M('stock_in_detail') ->getlastsql();
		return $polist;
	}
	
	public function getHistory($money_out_id){
		return M('money_out_history')->where(array('money_out_id'=>$money_out_id))->select();
	}

	public function getAutoCompletePo($filter_data){
		$data =  M('po')
			->join('left join vendors vendors on vendors.user_id=po.vendor_id')
			-> where($filter_data)
			-> field('po.id,po.vendor_id,vendors.company,po.total')
			->select();
			foreach ($data as $key => $value) {
				$where = 'refer_id='.$value['id'].' and refer_type_id=2 and status!=0';
				$data[$key]['payables'] = M('stock_in')->where($where)->getField('sum(buy_money)');
			}
		
		return $data;
	}

	public function getAutoCompleteRe($filter_data){
		$data =  M('ro')
			->join('left join `order` `order` on `order`.customer_id=ro.market')
			-> where($filter_data)
			-> field('`order`.payment_company,`order`.customer_id,ro.id,ro.total')
			->select();
			foreach ($data as $key => $value) {
				$where = 'refer_id='.$value['id'].' and refer_type_id=3 and status!=0';
				$data[$key]['payables'] = M('stock_in')->where($where)->getField('sum(buy_money)');
			}
		return $data;
	}
	
	public function getIn(){
		$sql = "SELECT
	po.id,
	(
		SELECT
			(
				sum( po_product.price)
			)
		FROM
			po_product
		WHERE
			po.id = po_product.po_id
	) AS total,
	po.user_id,
	vendors.company,
	po.vendor_id,
	(
		SELECT
			SUM(stock_in.buy_money)
		FROM
			stock_in
		WHERE
			stock_in.refer_id = po.id
		AND stock_in.refer_type_id = 2
		AND stock_in. STATUS = 2
	) AS stin
FROM
	po
LEFT JOIN vendors ON po.vendor_id = vendors.user_id
WHERE
	(
		`po`.date_added BETWEEN '2017-09-01'
		AND '9999-12-31'
	)
AND po.`status` != 0
AND po.`status` != 9";
	$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getRo(){
			$sql = "SELECT
	stock_in.in_id,
	w.company_name,
	w.telephone,
	w.customer_id,
	`ro`.id,
	stock_in.buy_money
FROM
	`stock_in`
LEFT JOIN `ro` ON `ro`.id = stock_in.refer_id
LEFT JOIN customer w ON w.customer_id = `ro`.market
WHERE
(`ro`.date_added BETWEEN '2017-08-01'AND '2017-09-20')
AND stock_in.`status` = 2";
		$query = $this->db->query($sql);
		return $query->rows;
	}


	public function getBillMoney($cur_month, $end_month) {
	    $map['year_month'] = array('between',array($end_month, $cur_month));
	    // $map['date_added'] = array('between',array($end_month, $cur_month));
	    // $map['vb.status'] = array('gt', 0);
	    $query = M('vendor_bill_new vb')
	      ->join('vendor_bill_money_out vbp on vb.vendor_bill_id=vbp.vendor_bill_id')
	      ->where($map)
	      ->field('vbp.money_out_id')
	      ->select();
		// echo M('vendor_bill_new')->getLastsql();

	    return $query;
  	}

  	public function getVendorIdsFromMoney($cur_month, $end_month, $billed_money_out_ids) {
   	 $complete_status = array('1'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		$map['trader_type'] = array('eq', 1);
		$map['refer_type_id'] = array('eq', 2);
		if(!empty($billed_money_out_ids)) {
			$map['money_out_id'] = array('not in', $billed_money_out_ids);	
		}
		$query = M('money_out')->where($map)->group('payee_id')->field('payee_id')->select();
		// echo M('money_out')->getLastsql();

		return $query;
  	}

  	public function getToByVendeyMoney($cur_month, $end_month, $billed_po_ids, $vendor_id = 0) {
		// $complete_status = array('4','6'); // 4=>'已收货', 6=>'审核完成'
		// $map['date_added'] = array('between',array($end_month, $cur_month));
		// $map['status'] = array('in', $complete_status);
		// if(!empty($billed_po_ids)) {
		// 	$map['id'] = array('not in', $billed_po_ids);	
		// }
		// $map['vendor_id'] = array('eq', $vendor_id);
		// $query = M('po')->where($map)->select();
  		$complete_status = array('1'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		$map['trader_type'] = array('eq', 1);
		$map['refer_type_id'] = array('eq', 2);
		if(!empty($billed_money_out_ids)) {
			$map['money_out_id'] = array('not in', $billed_money_out_ids);	
		}
		$map['payee_id'] = array('eq', $vendor_id);
		$query = M('money_out')->where($map)->select();
		// echo M('money_out')->getLastsql();

		return $query;
	}

	public function saveVendorBill($data, $monery_ids) {
		// var_dump($data);var_dump($monery_ids);die();
    $vendor_bill_id = M('vendor_bill_new')->add($data);
    foreach ($monery_ids as $money_out_id) {
      M('vendor_bill_money_out')->add(array('vendor_bill_id'=>$vendor_bill_id, 'money_out_id'=>$money_out_id));
      M('money_out')->where(array( 'money_out_id'=>$money_out_id))->save(array('status'=>6));
    }
    return $vendor_bill_id;
  }

  public function addVendorBillHistory($vendor_bill_id, $user_id, $operator_name, $comment) {
    $vendorBillHistory = M('vendor_bill_new_history');
    $data = array('vendor_bill_id'=>$vendor_bill_id, 'user_id'=>$user_id, 
      'operator_name'=>$operator_name, 'comment'=>$comment, 
      'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
    $vendorBillHistory->data($data)->add();
  }
  
   public function getdetailtotal($stock_in_ids){
	$in_id_arr = explode(',',$stock_in_ids );

	foreach ($in_id_arr as $key => $value) {
		if (!empty($value)) {
			$status = M('stock_in')->where(array('in_id'=>$value))->getField('status');
			if ($status==2) {
				$dtotal +=M('stock_in_detail')->where(array('in_id'=>$value))->getField('SUM(product_price*product_quantity)');
			}
      		
		}
	}
	return $dtotal;
  }
 
}